/*
 * 项目名称:    wms-server-jeecg
 * 创建人员:    gongwenkai
 * 创建时间:    2024-01-02
 */
package org.jeecg.modules.flow.callback.delivery.task;

import cn.hutool.core.collection.CollectionUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.business.delivery.service.IWmsDeliveryTaskService;
import org.jeecg.modules.business.third.service.ISapOperateService;
import org.jeecg.modules.dock.entity.dto.response.SapBaseResponseDTO;
import org.jeecg.modules.flow.callback.enums.SimpleDocumentTypeEnum;
import org.jeecg.modules.flow.callback.enums.TransferStatusEnum;
import org.jeecg.modules.flow.sys.common.BaseCustomBeanRun;
import org.jeecg.modules.flow.sys.entity.dto.BaseFlowDto;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 拨任务过账 回调Bean
 *
 * @author gongwenkai
 * @version 1.0.0
 * @since 2024-01-02
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class DeliveryTaskTransferBean<T> extends BaseCustomBeanRun<T> {

    private final ISapOperateService sapOperateService;

    private final IWmsDeliveryTaskService deliveryTaskService;

    /**
     * 业务逻辑
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void actureRun() {

        BaseFlowDto baseFlowDto = this.getBaseFlowDto();
        // 获取请求参数
        String taskId = baseFlowDto.getInfoId();
        Boolean successFlag=true;
        //调用第三方接口
        List<SapBaseResponseDTO> sapBaseResponseDTOList=new ArrayList<>();
        try{
            sapBaseResponseDTOList = sapOperateService.deliveryByTask(taskId);
        }catch (Exception e){
            log.error(e.getMessage());
            successFlag=false;
            baseFlowDto.setResult(Result.error(e.getMessage()));
            //更新过账状态 过账失败
            deliveryTaskService.updateTransferStatus(SimpleDocumentTypeEnum.DELIVERY_TASK,taskId, TransferStatusEnum.TRANSFER_FAIL);
        }
        if(!CollectionUtil.isEmpty(sapBaseResponseDTOList)){
            for(SapBaseResponseDTO sapBaseResponseDTO:sapBaseResponseDTOList){
                if("E".equals(sapBaseResponseDTO.getResult())){
                    successFlag=false;
                    baseFlowDto.setResult(Result.error(sapBaseResponseDTO.getMessage()));
                    //更新过账状态 过账失败
                    deliveryTaskService.updateTransferStatus(SimpleDocumentTypeEnum.DELIVERY_TASK,taskId, TransferStatusEnum.TRANSFER_FAIL);
                }
            }
        }
        if(successFlag){
            //更新过账状态 过账成功
            deliveryTaskService.updateTransferStatus(SimpleDocumentTypeEnum.DELIVERY_TASK,taskId, TransferStatusEnum.TRANSFER_SUCCESS);
            // 当前前端调用业务需要你返回的
            baseFlowDto.setResult(Result.OK());
        }
        // id是保存业务记录的id。用于生成业务流程信息记录
        baseFlowDto.setInfoId(taskId);
    }
}
